<?php


namespace app\user\controller;


use think\Controller;
use think\facade\Cache;
use think\Request;
use think\facade\Session;
use lib\AliPayPc;
class Order extends Controller
{

    public function setorder(){
        $sum_price=0;
        $total_num=0;
//        $user=Session::get('user');
//        $data=Cache::hgetAll('user_id_'.$user['id']);
//        foreach ($data as $k=>$v){                 //遍历键
//            $v=json_decode($v);
//            $a=db('goods')->field(['sale_price','thumb','goods_name'])->where('id',$k)->find();
//            foreach ($v as $key=>$value){
//                $arr[$k][$key]=$value;
//                $arr[$k]['sale_price']=$a['sale_price'];
//                $arr[$k]['thumb']=$a['thumb'];
//                $arr[$k]['goods_name']=$a['goods_name'];
//                $arr[$k]['id']=$k;
//            }
//            $arr[$k]['total_price']=$a['sale_price']*$arr[$k]['num'];    //单件商品总价
//            $sum_price+=$arr[$k]['total_price'];     //总价格
//            $total_num+=$total_num+$arr[$k]['num'];   //总数量
//            $sessarrid[]=$arr[$k]['id'];
//            $sessarrname[]=$arr[$k]['goods_name'].' * '.$arr[$k]['num'];
//        }
//        $ids='';
//        $names='';
//        foreach ($sessarrid as $k=>$v){
//            $ids.=$v.',';
//        }
//        foreach ($sessarrname as $k=>$v){
//            $names.=$v.',';
//        }
//        $ids=substr($ids,0,-1);
//        $names=substr($names,0,-1);
//        session('goods_id',$ids);
//        session('order_text',json_encode(['name'=>"$names"]));
//        if(empty($arr)){
//            $arr=1;
//        }
//        $this->assign(['arr'=>$arr,'sum_price'=>$sum_price,'total_num'=>$total_num]);
//        return view();
        $user=Session::get('user');
        $data=Cache::hgetAll('user_id_'.$user['id']);     //取得购物车的东西


        foreach ($data as $k=>$v){                 //遍历键
            $v=json_decode($v);

            $a=db('goods')->field(['sale_price','thumb','goods_name','reserve','onshelf'])->where('id',$k)->find();
           if($a['reserve']==0||$a['onshelf']==0){
               $this->error($a['goods_name'].'已售罄或已下架,请前往购物车自行删除,在生成新的订单','/user/cart/getcart');
           }
            foreach ($v as $key=>$value){
                $arr[$k][$key]=$value;
                $arr[$k]['sale_price']=$a['sale_price'];
                $arr[$k]['thumb']=$a['thumb'];
                $arr[$k]['goods_name']=$a['goods_name'];
                $arr[$k]['id']=$k;
            }

            $arr[$k]['total_price']=$a['sale_price']*$arr[$k]['num'];    //单件商品总价
            $sum_price+=$arr[$k]['total_price'];     //总价格
            $total_num=$total_num+$arr[$k]['num'];   //总数量
            $sessarrid[]=$arr[$k]['id'];
            $sessarrname[]=$arr[$k]['goods_name'].'×'.$arr[$k]['num'];
        }

        $ids='';
        $names='';
        foreach ($sessarrid as $k=>$v){
            $ids.=$v.',';
        }
        foreach ($sessarrname as $k=>$v){
            $names.=$v.',';
        }
        $ids=substr($ids,0,-1);
        $names=substr($names,0,-1);
        session('goods_id',$ids);

        session('order_text',json_encode(['name'=>"$names"]));
        if(empty($arr)){
            $arr=1;
        }
        $orderid=date('YmdHis').rand(10000,99999);//订单号

        //地址
        $addresses=db('address')->where('name',$user['name'])->select();
        $oneaddress=db('address')->where('name',$user['name'])->find();
        $this->assign(['arr'=>$arr,'sum_price'=>$sum_price,'total_num'=>$total_num,'orderid'=>$orderid,'addresses'=>$addresses,'oneaddress'=>$oneaddress]);
        return view();

        }

    //支付
    public function MtAliPay(Request $request)
    {
//        dump(\session('goods_id'));
//        die();
//        $id=\session('goods_id');
//        dump($id);
//        $d= \session('order_text');
//        dump($d);
//        die();


        if(request()->isPost()){
            $user=Session::get('user');
            $addinfo=[
                'receiver'=>input('receiver'),
                'phone'=>input('phone'),
                'address'=>input('address')
            ];

            Cache::hset('user_address_id_'.$user['id'],input('post.orderid'),json_encode($addinfo));
            Cache::expire('user_address_id_'.$user['id'],3600);
            $hasorder=Cache::hgetall('user_order_id_'.$user['id']);
            if (!empty($hasorder)){
                $this->error('您有一笔待支付的订单,请处理完在生成新的订单','/order');
            }
        $data=Cache::hgetAll('user_id_'.$user['id']);     //取得购物车的东西
        foreach($data as $k=>$v){
            $v=json_decode($v);                          //获得购物车的数量
            foreach($v as $key=>$value){
                $arro[$key]=$value;
                $arro['goodsid']=$k;
            }

                $orderidandgid=input('post.orderid').'+'.$k;
                Cache::hset('user_order_id_'.$user['id'],$orderidandgid,json_encode($arro));

                //

                Cache::expire('user_order_id_'.$user['id'],3600);
            }
        //获取收获地址

        }
//        $infoadd=Cache::hget('user_address_id_'.$user['id'],input('post.orderid'));
//        $infoadd=json_decode($infoadd);
//        $data['address']=$infoadd->address;
//        $data['phone']=$infoadd->phone;
//        $data['receiver']=$infoadd->receiver;
//        dump($infoadd);
//        dump($data);
//        die();
        //$buygoods=Cache::hget('user_order_id_'.$user['id']);
//        foreach ($buygoods as $k=>$v){
//            $v=json_decode($v);
//            $orderid=explode('+',$k);
//        }

        //if(isset(session('order_text')))

        \session('orderid',input('orderid'));


        $name=json_decode(\session('order_text'));

        if (isset($name)){
            $text=$name->name;
        }
        $maytext=input('text');
        if (isset($maytext)){
            $text=$maytext;
        }

        $goodsid=input('goods_id');
        if(!empty($goodsid)){

            session('goods_id',$goodsid);
        }
        $id=\session('goods_id');

        //dump($name->name);

        $data=input('post.');

        //dump($data);
        $out_trade_no = input('orderid');//订单号
        $subject =$text ;//商品名称
        $total_amount = (float)input('price');//商品金额 元

        \session('order_id',$out_trade_no);
        \session('order_text',$subject);
        \session('total_price',$total_amount);

        $body = $subject;//商品描述
        $config_data = [
            'return_url'=>$request->domain().'/user/order/redict',//同步跳转 待写
            'notify_url'=>$request->domain().'/tp5.1test/public/index.php/index/callback/notify_url',//异步跳转 待写
            'app_id' => "2016102700770126",

            //商户私钥
            'merchant_private_key' =>"MIIEowIBAAKCAQEAhyYMpMRMmlsjqSyyEJZjJo07DH63A1CaTE/JsXKbYegF+Yl/7mN5Cdjo4NHCEWhQWfpNh/tZC9mdFWvN3fpXBdCbEGANAnJIRhRPTHqI/RFbc9nIn7X//HRgU2CnkSWPfoXKz3eFqNw8z83ELcBd/Cp91wjS8g1y1ODH5SQ750Et/GYvinuX5DjykwQ/hzGu2he/B3qEIjum6zaHkZftE4ibZQTIdA+Eu1UZVZvB9i3alBlZh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YAK6Cw7EMz9pPw0zxGWfviOTUqPhWqr4mGk7GlZv2Cqs/zLZjwVlvL/6UuaLMmayLb+ckqyEi90aycSPNsjI7wKBgFzgUEJZReOYdb9B6NxhthrNCKDm8nZNBhA0+RXBOmH+I0Oe9bwSENUHEfsLa6a7lCqDxB3F0CgOcCFcqgDUDBnDoyn3iGAu+UhrlMK3e6+yeCe6RQxyjEBf3FYepji8vJFOp9jtQVZ6zN/ocP7gqoHYhAN9OXkc4Al4zh9hxd/j",

            //编码格式
            'charset' => "UTF-8",

            //签名方式
            'sign_type'=>"RSA2",

            //支付宝网关
            'gatewayUrl' => "https://openapi.alipaydev.com/gateway.do",

            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhyYMpMRMmlsjqSyyEJZjJo07DH63A1CaTE/JsXKbYegF+Yl/7mN5Cdjo4NHCEWhQWfpNh/tZC9mdFWvN3fpXBdCbEGANAnJIRhRPTHqI/RFbc9nIn7X//HRgU2CnkSWPfoXKz3eFqNw8z83ELcBd/Cp91wjS8g1y1ODH5SQ750Et/GYvinuX5DjykwQ/hzGu2he/B3qEIjum6zaHkZftE4ibZQTIdA+Eu1UZVZvB9i3alBlZhrTpJQ3Pt/xcJqfPqiiXzhFbcZm+h7p7VJgnBTrrchOebV2X9u/zhPlD3nP3pEFiBDALVNEwTumW83TB8eLzr6X+FuhDp9kBaO8IqQIDAQAB"

        ];

        //因为声明为静态类，所以直接调用
        AliPayPc::setAilPay($out_trade_no,$subject,$total_amount,$body,$config_data);
    }
    //跳转
    public function redict(){
        //清空购物车
//        $user=Session::get('user');
//        $data=Cache::hgetAll('user_id_'.$user['id']);
//        foreach ($data as $k=>$v){
//            Cache::hDel("user_id_".$user['id'],$k);
//        }
        //把订单删除了
        $user=Session::get('user');
        
        
        //$user=Session::get('user');
        $data['order_id']=\session('order_id');
        $data['user_id']=$user['id'];
        $data['order_text']=\session('order_text');
        $data['goods_id']=\session('goods_id');
        $data['total_price']=\session('total_price');
        $orderid=\session('orderid');
        $infoadd=Cache::hget('user_address_id_'.$user['id'],$orderid);
        $infoadd=json_decode($infoadd);

        $data['address']=$infoadd->address;
        $data['phone']=$infoadd->phone;
        $data['receiver']=$infoadd->receiver;
        \session('address',$infoadd->address);
        \session('phone',$infoadd->phone);
        \session('receiver',$infoadd->receiver);
        db('order')->insert($data);

        $goods_ids=explode(',',\session('goods_id'));
        $goods=explode(',',$data['order_text']);
        foreach ($goods as $k=>$v){
            $goods_num=explode('×',$v);
            $num[]=$goods_num[1];
        }
        foreach ($goods_ids as $k=>$v){
            db('comment')->insert(['user_id'=>$data['user_id'],'goods_id'=>$v,'date'=>date('Y-m-d H:i:s'),'order_id'=>$data['order_id'],'num'=>$num[$k]]);
            db('goods')->where('id',$v)->setInc('sale_num',(int)$num[$k]);
            db('goods')->where('id',$v)->setDec('reserve',(int)$num[$k]);
        }
        Cache::expire('user_address_id_'.$user['id'],1);
        Cache::expire('user_order_id_'.$user['id'],1);
        Cache::expire('user_id_'.$user['id'],1);
        return $this->redirect('paysuccess');
    }

    //支付成功后把购买的商品插进评论数据库
    public function paysuccess(){
        $data['order_id']=\session('order_id');
        $data['order_text']=\session('order_text');
        $data['total_price']=\session('total_price');
        $data['address']=\session('address');
        $data['phone']=\session('phone');
        $data['receiver']=\session('receiver');
        if(!empty($data['order_id'])){
            $this->assign([
                'order_id'=>$data['order_id'],
                'order_text'=>$data['order_text'],
                'total_price'=>$data['total_price'],
                'address'=>$data['address'],
                'phone'=>$data['phone'],
                'receiver'=>$data['receiver']
            ]);
            return view();
        }else{
            $this->error('你并没有购买任何东西','/');
        }

    }

    //取消订单
    public function cancelorder(){
        $user=Session::get('user');
        $data=Cache::expire('user_order_id_'.$user['id'],1);
        $data=Cache::expire('user_address_id_'.$user['id'],1);
        echo 1;
    }

    //确认收货
    public function issure(){
        db('order')->where('order_id',input('order_id'))->update(['is_sure'=>1]);
        echo 1;
    }
}